from django.contrib.auth.models import User
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth import logout as auth_logout, login as auth_login
from message.models import Message



def index(request):
    if not request.user.is_anonymous:
        return render(request, 'index.html')
    else:
        return redirect('login')

def login(request):
    if request.method == "GET":
        return render(request,'login.html')
    username = request.POST.get('username')
    password = request.POST.get('password')
    remember = request.POST.get('remember')
    user = User.objects.filter(username=username)
    if not user.exists():
        return JsonResponse({'code':400,'msg':'用户名不存在'})
    user = user.first()
    if not user.check_password(password):
        return JsonResponse({'code': 400, 'msg': '账户名或密码错误'})
    auth_login(request, user)
    if remember == 'false':
        request.session.set_expiry(0)  # 浏览器关闭后，session过期
    return JsonResponse({'code': 200, 'msg': '登录成功'})

def logout(request):
    auth_logout(request)
    return redirect(to='login')

def register(request):
    if request.method == 'GET':
        return render(request,'register.html')
    username = request.POST.get('username')
    password = request.POST.get('password')
    email = request.POST.get('email')
    user = User.objects.filter(username=username)
    if user.exists():
        return JsonResponse({'code':400, 'msg':'用户名已存在'})
    User.objects.create_user(username=username,password=password,email=email)
    return JsonResponse({'code':200, 'msg':'注册成功'})

def get_user(request):
    user_list = User.objects.values('id','username').exclude(username=request.user.username)
    user_list = list(user_list)
    for user in user_list:
        if queryset := Message.objects.filter(
        (Q(send_id=request.user.pk)& Q(recv_id=user.get('id'))) | (Q(send_id=user.get('id'))& Q(recv_id=request.user.pk))).last():
            user['text'] = queryset.text
    return JsonResponse({'code':200, 'userList':user_list})

def get_msg(request):
    send_id = request.GET.get('id')
    text_list = Message.objects.values('text','created_time','send_id').filter(
        (Q(send_id=request.user.pk)& Q(recv_id=send_id)) | (Q(send_id=send_id)& Q(recv_id=request.user.pk)))
    text_list = text_list.order_by('pk')
    user = User.objects.get(id=send_id).username
    return JsonResponse({'code':200, 'textList':list(text_list),'user':user})

def send_msg(request):
    text = request.POST.get('text')
    recv_id = request.POST.get('id')
    Message.objects.create(text=text,recv_id=recv_id,send_id=request.user.pk)
    return JsonResponse({'code':200, 'msg':'发送成功'})